package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.RequestUtils;
import com.settlement.system.listener.easyexcel.SysLogRecordListener;
import com.settlement.system.model.entity.SysLogRecord;
import com.settlement.system.model.form.SysLogRecordForm;
import com.settlement.system.model.query.SysLogRecordQuery;
import com.settlement.system.model.vo.SysLogRecordImportVo;
import com.settlement.system.service.SysLogRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 日志记录表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-06-20
 */
@RestController
@RequestMapping("/api/v1/logRecord")
@RequiredArgsConstructor
public class SysLogRecordController {

    @Value("${system.config.secret}")
    private String secret;

    @Value("${system.config.appId}")
    private String appId;

    private final SysLogRecordService sysLogRecordService;

    @GetMapping("/page")
    public PageResult<SysLogRecord> getPage(@ParameterObject SysLogRecordQuery queryParams) {
        Page<SysLogRecord> result = sysLogRecordService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存日志记录表")
    @PostMapping("saveLog")
    @PreventDuplicateSubmit
    public Result<?> saveSysLogRecord(HttpServletRequest request, @RequestBody @Valid SysLogRecordForm sysLogRecordForm) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        sysLogRecordService.saveSysLogRecord(sysLogRecordForm);
        return Result.success();
    }

    @Operation(summary = "流程运行成功")
    @PostMapping("success")
    @PreventDuplicateSubmit
    public Result<?> success(HttpServletRequest request, @RequestBody @Valid SysLogRecordForm sysLogRecordForm) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        sysLogRecordService.success(sysLogRecordForm);
        return Result.success();
    }

    @Operation(summary = "获取日志记录表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysLogRecordForm> getSysLogRecordFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysLogRecordForm sysLogRecord = sysLogRecordService.getSysLogRecordFormData(id);
        return Result.success(sysLogRecord);
    }

    @Operation(summary = "删除日志记录表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:logRecord:delete')")
    public Result<?> deleteSysLogRecord(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysLogRecordService.deleteSysLogRecord(ids);
        return Result.judge(result);
    }

    @Operation(summary = "日志记录表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysLogRecordImport")
    @PreAuthorize("@ss.hasPerm('sys:logRecord:import')")
    @PreventDuplicateSubmit
    public Result<?> sysLogRecordImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysLogRecordListener listener = new SysLogRecordListener();
        EasyExcelFactory.read(file.getInputStream(), SysLogRecordImportVo.class, listener).sheet(0).doRead();
        List<SysLogRecordImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        sysLogRecordService.importData(list);
        return Result.success();
    }

    @Operation(summary = "导出日志记录表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:logRecord:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "日志记录表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<SysLogRecordImportVo> sysLogRecordList = sysLogRecordService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysLogRecordImportVo.class).sheet("日志记录表").doWrite(sysLogRecordList);
    }
}

